package cn.szzsi.model;

import cn.szzsi.common.util.CommonUtil;
import cn.szzsi.model.base.BaseMemberRank;
import com.jfinal.plugin.activerecord.Db;

import java.util.List;

/**
 * 实体类 - 会员等级
 * 
 */
public class MemberRank extends BaseMemberRank<MemberRank> {

	private static final long serialVersionUID = 5042501344569904747L;
	
	public static final MemberRank dao = new MemberRank().dao();
	
	/**
	 * 获取默认会员等级.
	 * 
	 */
	public MemberRank getDefaultMemberRank(String shopId) {
		MemberRank defaultMemberRank = dao.findFirst("select * from sys_member_rank where isDefault=? and shopId=? limit 1",1,shopId);
		if(defaultMemberRank == null) {
			defaultMemberRank = dao.findFirst("select * from sys_member_rank where shopId=? order by createDate asc",shopId);
		}
		return defaultMemberRank;
	}
	
	/**
	 * 根据积分获取符合此积分条件的最高会员等级，若不存在则返回null
	 * 
	 */
	public MemberRank getUpMemberRankByPoint(Integer point, String shopId) {
		String sql = "select * from sys_member_rank  where point <= ? and shopId=? order by point desc";
		return dao.findFirst(sql,point,shopId);
	}
	
	
	/**
	 * 根据积分获取会员等级，若不存在则返回null
	 * 
	 */
	public MemberRank getMemberRankByPoint(Integer point, String shopId) {
		String sql = "select * from sys_member_rank  where point = ? and shopId=? ";
		return dao.findFirst(sql, point,shopId);
	}
	
	/**
	 * 重写方法，保存时若对象isDefault=true，则设置其它对象isDefault值为false
	 * 
	 */
	public void save(MemberRank memberRank) {
		if (memberRank.getBoolean("isDefault")!=null && memberRank.getBoolean("isDefault")) {
			String sql = "select * from sys_member_rank where isDefault = ? and shopId = ?";
			List<MemberRank> memberRankList = dao.find(sql,true,memberRank.getStr("shopId"));
			if (memberRankList != null) {
				for (MemberRank r : memberRankList) {
					r.set("isDefault", false);
					r.update();
				}
			}
		}
		memberRank.set("id", CommonUtil.getUUID());
		memberRank.save();
	}
	
	/**
	 * 重写方法，更新时若对象isDefault=true，则设置其它对象isDefault值为false
	 * 
	 */
	public void update(MemberRank memberRank) {
		if (memberRank.getBoolean("isDefault")) {
			MemberRank memberRank1= MemberRank.dao.findById(memberRank.getStr("id"));
			Db.update("update sys_member_rank set isDefault = 0 where shopId=?",memberRank1.getStr("shopId"));
			Db.update("update sys_member_rank set isDefault = 1 where id = ?",memberRank1.getStr("id"));
		}
		memberRank.update();

	}
	
	/**
	 * 获取所有实体对象总数.
	 * 
	 * @return 实体对象总数
	 */
	public Long getTotalCount(String shopId) {
		String sql = "select count(*) from sys_member_rank where shopId = ?";
		return Db.queryLong(sql,shopId);
	}
	
	/* getter */
	public List<Member> getMember(){
		System.out.println(getId());
		String sql = "select * from sys_member where memberRank_id = ?";
		return Member.dao.find(sql,getStr("id"));
		
	}
	
	public List<MemberRank> getAll(String shopId){
		String sql = "select * from sys_member_rank where shopId = ?";
		return dao.find(sql,shopId);
	}
}
